//Ext.namespace('Vector.Graph');
Vector.Graph.checkData = function(obj){
	if(obj.graphData){
		return obj.graphData;
	}else{
		return null;
	}
};
/**
 * @class Vector.Graph.LineGraph
 * Simple Vector Line Graph class
 * @cfg {Object} graphData array of array object 
 * Example: [[{x:0,y:5},{x:1,y:10}],[{x:0,y:8},{x:1,y:13}]]
 * @constructor
 * Create a new line
 * @param {Object} config The config object
 */
Vector.Graph.LineGraph = function(config){
	Ext.apply(this,config);
	var lines = [];
	var colors = ['blue', 'green', 'grey', 'red'];
	this.rawData = Vector.Graph.checkData(config);
//	return{
		/**
		 * Add and draw a line on the graph
		 * @param obj {Array} multi array of values to graph
		 */
		this.drawLine = function(obj){
			if(!this.poly){this.poly = Vector.VectorManager.getPoly({parent: this.group.id});}
			if(obj){
				for(var i=0; i<obj.length; i++) {
					this.rawData.push(obj[i]);
				}
			}
//			for(var i=0; i<obj.length; i++) {
//				this.rawData.push(obj[i]);
			   	this.baseCalcs(this.rawData);
			   	
			   	this.graphData = this.rescaleData(this.rawData);
			   	this.graphData = this.adjustData(this.graphData);
			   	this.clearLineStore();
			   	this.addLines(this.graphData);
			   	this.Axis.deleteAll();
			   	this.drawAxis();
//				this.poly.render(lines[lines.length - 1]);	
//			}
		};
//		setupGraph: function(obj){
//			this.rawData = obj.graphData;
//		},
		this.baseCalcs = function(data){
			this.lengthY = this.height - this.mainY;
			this.lengthX = this.width - this.mainX;
			this.x = this.getMaxX(data);
			this.y = this.getMaxY(data);	
		};
		this.drawAxis = function(){
					this.Axis = Vector.VectorManager.getLine({parent: this.group.id});
			this.Axis.addItems([{id: 'xLine',
				strokecolor: 'steelblue',
				strokeweight: '1px',
				fromx:this.mainX,
				fromy:this.mainY,
				tox:this.lengthX,
				toy:this.mainY}
				,{id: 'yLine',
				strokecolor: 'steelblue',
				strokeweight: '1px',
				fromx:this.mainX,
				fromy:this.mainY,
				tox:this.mainX,
				toy:this.lengthY}]);
			this.Axis.renderAll();
		};
		this.clearLineStore = function(){
			lines = [];
			this.poly.deleteAll();
		};
		this.renderGraph = function(renderTo){
	        this.graphTemplate = new Ext.Template('<div></div>').compile();
			this.container = Ext.get(renderTo);
			this.width = this.container.getWidth();
			this.height = this.container.getHeight();
			this.el = this.graphTemplate.append(this.container.dom, [''], true);
			var snap = new Ext.Resizable(this.el, {
			    pinned:false,
			    width:250,
			    height:100,
			    handles: 'e',
			    widthIncrement:50,
			    minWidth: 50,
			    dynamic: true
			});
			this.el.addClass('graph-main');
			this.el.setHeight(this.height);
			this.el.setWidth(this.width);
			this.mainX = 25;
			this.mainY = this.height -25;
			
			this.baseCalcs(this.rawData);
			
			var colorIndex = 0;
			var vm = Vector.VectorManager;
			
			this.graphData = this.rescaleData(this.rawData);
			this.graphData = this.adjustData(this.graphData);
			this.c = vm.getCanvas({parent: this.el.id});
			this.group = Vector.VectorManager.getGroup({parent: this.c.id,height: this.height,width: this.width});
			this.group.render();
			
			this.graphBox = Vector.VectorManager.getBox({parent: this.group.id});
			this.graphBox.render({strokecolor: 'green',strokeweight: '2',height: this.height,width: this.width});

			this.drawAxis();
			
	    	this.poly = Vector.VectorManager.getPoly({parent: this.group.id});
		    this.addLines(this.graphData);
			this.poly.addItems(lines);
			this.poly.renderAll();
			
			this.legendGroup = Vector.VectorManager.getGroup(
				{	parent: this.c.id,
					height: 60,
					width: 120,
					left: (this.width - 125),
					top: 5});
			this.legendGroup.render();
			
			this.legend = Vector.VectorManager.getRoundBox({parent: this.legendGroup.id,opts: {fill:'white'}});
			this.legend.render({stroke: 'gray',height: 60,width: 120,shadow:true});
			
			this.legendLine = Vector.VectorManager.getLine({parent: this.legendGroup.id});
			this.legendLine.addItems([{strokecolor:lines[0].strokecolor,fromx:75,fromy:20,tox:115,toy:20}
			,{strokecolor:lines[1].strokecolor,fromx:75,fromy:45,tox:115,toy:45}]);
			this.legendLine.renderAll();

			this.legendBox = Vector.VectorManager.getBox({parent: this.legendGroup.id});
			this.legendBox.addItems([{cls:'graph-legend',strokecolor:'none',text:'series 1',height:'25px',width:'60px',left:2,top:2,shadow:'false'}
			,{cls:'graph-legend',strokecolor:'none',text:'series 2',height:'25px',width:'60px',left:2,top:34,shadow:'false'}]);
			this.legendBox.renderAll();
		};
		this.addLines = function(ob){
			for(var i=0; i<ob.length; i++) {
			    	var p = [];
		    		for(var j=0; j<ob[i].length; j++) {
		    			p.push(ob[i][j].x + ' ' + ob[i][j].y); 
		    		}
		    		lines.push({stroke: colors[i],strokeweight: '1',pts: p.join(' ')});
		    	}
		};
		this.scaleX = function(){return parseFloat(this.x/(this.lengthX-this.mainX));};
		this.scaleY = function(){return parseFloat(this.y/(this.mainY-this.lengthY));};
		this.rescaleData = function(gData){
			var newData = new Array(gData.length);
	    	for(var i=0; i<gData.length; i++) {
	    		newData[i] = new Array(gData[i].length);
	    		for(var j=0; j<gData[i].length; j++) {
	    			newData[i][j] = {x:(gData[i][j].x / this.scaleX()),y:(gData[i][j].y / this.scaleY())};
	    		}
	    	}
	    	return newData;
	    };
	    this.adjustData = function(gData){
	    	var d = new Array(gData.length);
	    	for(var i=0; i<gData.length; i++) {
	    		d[i] = new Array(gData[i].length);
	    		for(var j=0; j<gData[i].length; j++) {
	    			d[i][j] = {x:(gData[i][j].x + this.mainX),y: (this.mainY - gData[i][j].y)};
	    		}
	    	}
	    	return d;
	    };
	    this.getMaxX = function(obj){
	    	var m = 0;
		    	for(var i=0; i<obj.length; i++) {
		    		for(var j=0; j<obj[i].length; j++) {
			    		(m<obj[i][j].x)?m=obj[i][j].x:'';	
		    		}
	    	}
	    	this.maxX = m;
	    	return m;
	    };
	    this.getMaxY = function(obj){
	    	var m = 0;
		    	for(var i=0; i<obj.length; i++) {
		    		for(var j=0; j<obj[i].length; j++) {
			    		(m<obj[i][j].y)?m=obj[i][j].y:'';	
		    		}
		    	}
	    	this.maxY = m;
	    	return m;
	    };
	}
//}

/*
    object with:
    id-> id of the element (div) to
    be used to create the chart.
    width(optional)->width of the chart.
    height(optional)->height of the chart
    idLegend(optional)-> id of the element where legend will be rendered
*/
Vector.Graph.Barchart=function(config){
    
        this.id=config.id;
        this.el=getEl(config.id);
        this.el.addClass("Barchart");
        this.width=500;
        this.height=500;
        this.legendHeight=100,
        this.legendWidth=100
        Ext.util.Config.apply(this,config);
}
Vector.Graph.Barchart.prototype={
    /*
        Add an item to the chart
        @item {object) with :
        value - The value (in percent) of the bar to render
        label (optional)- The label of the element (for a legend)
        color(optional)- The color of the bar , if empty a random color is generated 
    */
    addItem:function(item){
        if(this.items==null){
            this.items=[];
        }
        this.items.push(item);

    },
   
    /*
        renders the chart 
        id--optional to render a legend to the element of the id
    */
    render:function(){

         if(this.items==null){
            if(this.isServer){
                 this.CallServer();
            }
            return;
         }
         /*
            GraphBox
            
         */
        var vm = Vector.VectorManager;
       
        this.group = vm.getGroup(this.el,
             {
                height: this.height,
                width: this.width
             });
        this.graphBox = vm.getBox(this.group.getEl(),
         {
            strokecolor: 'gray',
            height: this.height,
            width: this.width
         });
         
         var lastTop=10;
        
         for(var i=0;i< this.items.length;i++){
            if(i!=0)
                lastTop+=i+40;
                vm.getBox(this.group.getEl(),
                    {
                        strokecolor:this.randomBg(this.items[i]),
                        height:'20px',
                        width:this.width*this.items[i].value/100+"px",
                        left:20,
                        top:lastTop,
                        shadow:'true',
                        fillcolor:this.items[i].color
                       
                     }
              );
            
              vm.getBox(this.group.getEl(),
                {
                 cls:'graph-legend',
                 strokecolor:'white',
                 text:this.items[i].value+"%",
                 height:'25px',
                 width:'60px',
                 left: (this.width -130),
                 top:lastTop,
                 shadow:'false'
                }
               );
            
         }
        
         
          this.renderLegend();
        
        
         
    },

    /*
        Gets a random Background color for each bar
    */
    randomBg:function(item) {
        if(item.color){
            return item.color;
        }
        var hex1=new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F")
        var hex2=new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F")
        var hex3=new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F")
        var hex4=new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F")
        var hex5=new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F")
        var hex6=new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F")
        var bg="#"+hex1[Math.floor(Math.random()*hex1.length)]+hex2[Math.floor(Math.random()*hex2.length)]+hex3[Math.floor(Math.random()*hex3.length)]+hex4[Math.floor(Math.random()*hex4.length)]+hex5[Math.floor(Math.random()*hex5.length)]+hex6[Math.floor(Math.random()*hex6.length)]
        item.color=bg;
        return bg;
    },
    /*
        Tels the chart that the data will be server-side loaded
        and what page to call to get the data
    */
    setDataSource:function(sUrl){
       this.Url=sUrl;
       this.isServer=true;
       
    } ,
    /*
        private ->Calls the server-side page 
        to get the data
    */
    CallServer:function(){
        var callback =
        {
          success: this.HandleSuccess,
          failure: function(o) {alert("Error "+o.responseText);},
          scope:this
        }
        var transaction = YAHOO.util.Connect.asyncRequest('POST', this.Url, callback, "foo=bar");
    },
    HandleSuccess:function(resp){
        
        this.items=eval(resp.responseText);
        this.render();
        
    },
    /*
        Renders the chart legend
    */
    renderLegend:function(){
         var vm = Vector.VectorManager;
         
         this.legendGroup = vm.getGroup(this.group.getEl(),
         {
            height: this.legendHeight,
            width: this.legendWidth,
            left: (this.width + 50),
            top: 5
         }
         );
        
         this.legend = vm.getRoundBox(this.legendGroup.getEl(),
          {
            strokecolor: 'gray',
            height: this.legendHeight,
            width: this.legendWidth
          
          }
         );
         var dist=32;//distance between legends
         var distLine=32;//distance between lines
         var iniL=30;
         var iniB=17;
         for(var i=0;i< this.items.length;i++){
            vm.getLine(this.legendGroup.getEl(),{strokecolor:this.items[i].color,fromx:20,fromy:iniL,tox:35,toy:iniL,strokeweight: '5px'});
            vm.getBox(this.legendGroup.getEl(),{cls:'graph-legend',strokecolor:'white',text:this.items[i].label,height:'25px',width:'160px',left:40,top:iniB,shadow:'false'});
            iniL+=distLine;
            iniB+=dist;
         }
        
    }  
}